package com.itzw.hospital.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itzw.hospital.common.R;
import com.itzw.hospital.dto.DoctorDto;
import com.itzw.hospital.entity.Department;
import com.itzw.hospital.entity.Doctor;
import com.itzw.hospital.entity.Registration;
import com.itzw.hospital.mapper.DepartmentMapper;
import com.itzw.hospital.mapper.DoctorMapper;
import com.itzw.hospital.mapper.RegistrationMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/registration")
public class RegistrationController {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private DoctorMapper doctorMapper;

    @Autowired
    private RegistrationMapper registrationMapper;

    /**
     * 查询所有科室
     * @return
     */
    @GetMapping("/department")
    public R department(){
        List<Department> departmentList = departmentMapper.selectList(null);
        return R.success(departmentList);
    }

    /**
     * 根据科室id查询医生信息
     * @param departId
     * @return
     */
    @GetMapping("/doctor/{departId}")
    public R doctor(@PathVariable int departId){


        LambdaQueryWrapper<Doctor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Doctor::getDepartId,departId);
        List<Doctor> doctorList = doctorMapper.selectList(queryWrapper);

        List<DoctorDto> doctorDtoList = new ArrayList<>();
        BeanUtils.copyProperties(doctorList,doctorDtoList);

        doctorDtoList = doctorList.stream().map((item)->{
            DoctorDto doctorDto = new DoctorDto();
            BeanUtils.copyProperties(item,doctorDto);
            Integer itemDepartId = item.getDepartId();
            Department department = departmentMapper.selectById(itemDepartId);
            String departmentName = department.getName();
            doctorDto.setDepartmentName(departmentName);
            return doctorDto;
        }).collect(Collectors.toList());

        return R.success(doctorDtoList);
    }

    /**
     * 用户挂号
     * @param registration
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody Registration registration){
        Integer userId = registration.getUserId();
        LambdaQueryWrapper<Registration> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Registration::getUserId,userId);
        Registration registration1 = registrationMapper.selectOne(queryWrapper1);
        if (registration1 != null){
            return R.error("您已挂号成功,请勿重复挂号");
        }else {
            registration.setCreateTime(LocalDateTime.now());
            Integer count = registrationMapper.selectCount(null);
            if (count == 0){
                registration.setSort(1);
            }else {
                LambdaQueryWrapper<Registration> queryWrapper = new LambdaQueryWrapper();
                queryWrapper.orderByDesc(Registration::getSort).last("limit 1");
                Registration reg = registrationMapper.selectOne(queryWrapper);
                registration.setSort(reg.getSort()+1);
            }
            registration.setWaitingTime(count*2);
            registrationMapper.insert(registration);
            return R.success("您已挂号成功");
        }
    }

    /**
     * 查询所有挂号信息
     * @return
     */
    @GetMapping("/query")
    public R query(){
        LambdaQueryWrapper<Registration> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Registration::getSort);
        List<Registration> registrationList = registrationMapper.selectList(queryWrapper);
        return R.success(registrationList);
    }

    /**
     * 根据id删除挂号信息
     * @param id
     * @return
     */
    @Transactional
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable Integer id){
        Registration registration = registrationMapper.selectById(id);
        int count = registrationMapper.deleteById(id);
        if (count > 0){
            Integer sort = registration.getSort();
            System.out.println(sort);
            List<Registration> registrationList = registrationMapper.selectList(null);
            System.out.println("=============================1============================");
            for (int i = 0; i < registrationList.size(); i++) {
                System.out.println(registrationList.get(i));
            }
            if (registrationList == null){
                return R.success("删除挂号成功");
            }else {
                System.out.println("=========================2============================");
                for (int i = 0; i < registrationList.size(); i++) {
                    Registration reg = registrationList.get(i);
                    System.out.println(reg.getSort());
                    if (reg.getSort() > sort){
                        reg.setWaitingTime(reg.getWaitingTime()-2);
                        int ret = registrationMapper.updateById(reg);
                        System.out.println("==========================3===============================");
                        System.out.println(reg.getSort());
                    }
                }
                return R.success("删除挂号成功");
            }

        }else {
            return R.success("删除挂号失败");
        }
    }

    @PutMapping("/update")
    public R update(@RequestBody Registration registration){
        int i = registrationMapper.updateById(registration);
        if (i == 0){
            return R.error("修改挂号信息失败");
        }
        return R.success("修改挂号信息成功");
    }
    /**
     * 根据id查询挂号信息
     * @param id
     * @return
     */
    @GetMapping("/query/{id}")
    public R<Registration> queryById(@PathVariable int id){
        Registration registration = registrationMapper.selectById(id);
        return R.success(registration);
    }

    /**
     * 根据用户id查询挂号信息
     * @param id
     * @return
     */
    @GetMapping("/query/user/{id}")
    public R<Registration> queryByUserId(@PathVariable int id){
        LambdaQueryWrapper<Registration> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Registration::getUserId,id);
        Registration registration = registrationMapper.selectOne(queryWrapper);
        return R.success(registration);
    }
    /**
     * 用户等待时间
     * @param docNumber
     * @param sort
     * @return
     */
    @GetMapping("/query/wait")
    public R<String> queryWait(String docNumber,int sort){
        LambdaQueryWrapper<Registration> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.lt(Registration::getSort,sort).eq(Registration::getDocNumber,docNumber);
        int count = registrationMapper.selectCount(queryWrapper);
        return R.success("预计等待时间:"+count*2+"分钟");
    }

}
